#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
using pii = pair<int, int>;
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
class Solution {
public:
    int maxDistance(vector<vector<int>>& grid)
    {
        int m = grid.size(), n = grid[0].size();
        vector<vector<bool>> sta(m, vector<bool>(n, false));
        queue<pii> q;
        int count = 0;
        for (int i = 0;i < m;i++)
        {
            for (int j = 0;j < n;j++)
            {
                if (grid[i][j] == 1)
                {
                    ++count;
                    sta[i][j] = true;
                    q.push({ i,j });
                }
            }
        }
        if (count == 0 || count == m * n) return -1;
        int ret = 0;
        while (!q.empty())
        {
            ++ret;
            //cout<<q.size()<<endl;
            int cnt = q.size();
            while (cnt--)
            {
                int a = q.front().first;
                int b = q.front().second;
                q.pop();
                for (int i = 0;i < 4;i++)
                {
                    int x = a + dx[i], y = b + dy[i];
                    if (x >= 0 && x < m && y >= 0 && y < n && sta[x][y] == false)
                    {
                        sta[x][y] = true;
                        q.push({ x,y });
                    }
                }
            }
        }
        return ret - 1;
    }
};